package com.xmcc.utill;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * 转换json
 */
@Slf4j
public class JsonUtil {
    private final static ObjectMapper objectMapper = new ObjectMapper();

    // json 转字符串：
    public static <T> String object2string(T t){
        if (t==null){
            return null;
        }
        try {
            return t instanceof String? (String) t :objectMapper.writeValueAsString(t);
        } catch (JsonProcessingException e) {
            log.info("JsonUtil: object2string exception,Object:{},exception:{}",t,e);
            return null;
        }
    }

    //字符串转对象  TypeReference<List<User>> tTypeReference：
    public static <T> T string2object(String str,TypeReference<T> tTypeReference){
        if (str==null){
            return null;
        }
        try {
            return tTypeReference.getType().equals(String.class)?(T)str:objectMapper.readValue(str,tTypeReference);
        } catch (IOException e) {
            log.info("JsonUtil: string2object exception,String:{},tTypeReference:{},exception:{}",str,tTypeReference,e);
            return null;
        }
    }

}
